package com.ruoyi.web.controller.fund;

import cn.hutool.core.io.file.FileWriter;
import com.google.gson.Gson;
import com.ruoyi.Electronic.domain.HouseRepairElectronicT;
import com.ruoyi.HouseErrorMsg;
import com.ruoyi.HouseException;
import com.ruoyi.ajax.AjaxTools;
import com.ruoyi.area.domain.HouseAreaT;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.DocUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.costQuery.domain.BillVO;
import com.ruoyi.costQuery.domain.HouseCostT;
import com.ruoyi.costQuery.domain.InvoiceVO;
import com.ruoyi.costQuery.domain.MessageVO;
import com.ruoyi.costQuery.http.HttpMethodUtil;
import com.ruoyi.costQuery.service.IHouseCostQueryTService;
import com.ruoyi.data.ControlTool;
import com.ruoyi.data.DataUtils;
import com.ruoyi.data.MD5;
import com.ruoyi.data.NumberData;
import com.ruoyi.data.domain.ParameterSingleT;
import com.ruoyi.date.DateFormater;
import com.ruoyi.door.domain.HouseDoorT;
import com.ruoyi.door.service.IHouseDoorTService;
import com.ruoyi.project.domain.HouseProjectT;
import com.ruoyi.project.domain.ParameterSingleVO;
import com.ruoyi.project.service.IHouseProjectTService;
import com.ruoyi.util.ExcelUtils;
import com.ruoyi.util.FileUtil;
import com.ruoyi.util.SysParamKey;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 缴费信息Controller
 * 
 * @author lijie
 * @date 2023-04-24
 */
@RestController
@RequestMapping("/fund/costQuery")
public class HouseCostQueryTController extends BaseController
{
    @Autowired
    private IHouseCostQueryTService houseCostQueryTService;

    @Autowired
    private IHouseDoorTService houseDoorTService;

    @Autowired
    private IHouseProjectTService houseProjectTService;
    private HttpServletResponse response;

    private String targetFileName;
    private String generateFileName;
//    private String urlWord="zanysoft.xyz:8433/PRINT/";
    private String urlWord="127.0.0.1:8433/PRINT/";

    /**
     * 查询缴费信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HouseCostT houseCostT) throws Exception {
        startPage();
        ControlTool controlTool = new ControlTool();
        if(houseCostT.getUserName()!=null){
            houseCostT.setUserName(MD5.encrypt(houseCostT.getUserName()));
        }
        List<HouseCostT> list = houseCostQueryTService.selectHouseCostTList(houseCostT);
        for (HouseCostT houseDoorVO : list) {
            houseDoorVO.setUserName(MD5.decrypt(houseDoorVO.getUserName()));
            houseDoorVO.setBillHttp(RuoYiConfig.getBillHttp() +houseDoorVO.getBillName()+".pdf");
            if(houseDoorVO.getBillName()!=null){
                houseDoorVO.setBillName("电子票");
            }
        }
        if(getDataTableSumJudge(list)){
            HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostSum(houseCostT);
            houseCostVO.setAreaName("合计");
            list.add(houseCostVO);
        }
        return getDataTable(list);
    }
 /**
     * 查询缴费信息列表
     */
    @GetMapping("/list1")
    public TableDataInfo list1(HouseCostT houseCostT) throws Exception {
        startPage();
        List<HouseCostT> list=new ArrayList<>();
        return getDataTable(list);
    }

    /**
     * 导出缴费信息列表
     */
    @Log(title = "缴费信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HouseCostT houseCostT) throws Exception {

        if(houseCostT.getUserName()!=null){
            houseCostT.setUserName(MD5.encrypt(houseCostT.getUserName()));
        }
        List<HouseCostT> list = houseCostQueryTService.selectHouseCostTList(houseCostT);
        for (HouseCostT vo:list){
            vo.setPapersCode(MD5.decrypt(vo.getPapersCode()));
            vo.setUserName(MD5.decrypt(vo.getUserName()));
            vo.setTel(MD5.decrypt(vo.getTel()));
        }
        if(getDataTableSumJudge(list)){
            HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostSum(houseCostT);
            houseCostVO.setAreaName("合计");
            list.add(houseCostVO);
        }
        ExcelUtil<HouseCostT> util = new ExcelUtil<HouseCostT>(HouseCostT.class);
        util.exportExcel(response, list, "缴费信息数据");
    }

    /**
     * 获取缴费信息详细信息
     */
    @GetMapping(value = "/{costId}")
    public AjaxResult getInfo(@PathVariable("costId") Long costId)
    {
        return AjaxResult.success(houseCostQueryTService.selectHouseCostTByCostId(costId));
    }

    /**
     * 获取缴费信息详细信息
     */
    @GetMapping(value = "/getPrint/{costId}")
    public AjaxResult getPrint(@PathVariable("costId") Long costId)
    {
        HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostTByCostId(costId);
        houseCostVO.setFormula(houseCostVO.getSpace()+"*"+houseCostVO.getPrice()+"*");
        houseCostVO.setMoneyTemp(NumberData.makeUpperCaseSum(houseCostVO.getCostMoney().toString()));
        return AjaxResult.success(houseCostVO);
    }


    /**
     * 修改缴费信息
     */
    @Log(title = "缴费信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HouseCostT houseCostT)
    {
        return toAjax(houseCostQueryTService.updateHouseCostT(houseCostT));
    }
    @GetMapping(value = "/print/{costId}")
    public AjaxResult print(@PathVariable("costId") Long costId){
        BillVO billVO1 = houseCostQueryTService.getBillDetailByBillNO(costId);
        return AjaxResult.success(billVO1);
    }

    @GetMapping("/applyCostQuery/{costId}")
    public AjaxResult applyCostQuery(@PathVariable("costId") Long costId) throws Exception {
        HouseCostT houseCostT = houseCostQueryTService.selectHouseCostTByCostId(costId);
        if(houseCostT.getUserName()!=null){
            houseCostT.setUserName(MD5.decrypt(houseCostT.getUserName()));
        }
        if(houseCostT.getTel()!=null){
            houseCostT.setTel(MD5.decrypt(houseCostT.getTel()));
        }
        ControlTool controlTool = new ControlTool();
        File file01 = new File(RuoYiConfig.getFilePath());
        WritableWorkbook workbook01 = jxl.Workbook.createWorkbook(file01);

        WritableSheet sheet01 = workbook01.createSheet("Sheet1", 0);

        // 一些临时变量，用于写到excel中
        Label cell01 = null;
        Label cell02 = null;
        Label cell03 = null;
        Label cell04 = null;
        Label cell05 = null;
        Label cell06 = null;
        Label cell07 = null;
        Label cell08 = null;
        Label cell09 = null;
        Label cell10 = null;
        Label cell11 = null;
        Label cell12 = null;

        String lineTxt = null;

        // 设置字体为宋体，11号
        WritableFont headerFont = new WritableFont(WritableFont.createFont("宋体"), 11, WritableFont.NO_BOLD, false,
                UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);

        WritableCellFormat headerFormat = new WritableCellFormat(headerFont);

        cell07 = new Label(1, 1, houseCostT.getHouseId(), headerFormat);
        cell01 = new Label(2, 1, houseCostT.getUserName(), headerFormat);
        cell02 = new Label(3, 1, houseCostT.getTel(), headerFormat);
        cell03 = new Label(4, 1, houseCostT.getAddr(), headerFormat);
        cell04 = new Label(5, 1, houseCostT.getSpace(), headerFormat);
        cell05 = new Label(6, 1, houseCostT.getSpace()+"*"+houseCostT.getPrice(), headerFormat);
        cell06 = new Label(7, 1, houseCostT.getCostMoney()+"", headerFormat);
        cell08 = new Label(8, 1, houseCostT.getPrice()+"", headerFormat);
        cell09 = new Label(9, 1, houseCostT.getCostId()+"", headerFormat);
        cell10 = new Label(10, 1, houseCostT.getCostBillType()+"", headerFormat);
        cell11 = new Label(11, 1, houseCostT.getCostBillWay()+"", headerFormat);
        cell12 = new Label(12, 1, houseCostT.getCreater()+"", headerFormat);
        sheet01.addCell(new Label(1, 0, "房屋编号", headerFormat));
        sheet01.addCell(new Label(2, 0, "交款人", headerFormat));
        sheet01.addCell(new Label(3, 0, "手机号", headerFormat));
        sheet01.addCell(new Label(4, 0, "地址", headerFormat));
        sheet01.addCell(new Label(5, 0, "住宅面积和数量", headerFormat));
        sheet01.addCell(new Label(6, 0, "交存计算", headerFormat));
        sheet01.addCell(new Label(7, 0, "金额", headerFormat));
        sheet01.addCell(new Label(8, 0, "标准", headerFormat));
        sheet01.addCell(new Label(9, 0, "缴费id", headerFormat));
        sheet01.addCell(new Label(10, 0, "交款人类型", headerFormat));
        sheet01.addCell(new Label(11, 0, "收款方式", headerFormat));
        sheet01.addCell(new Label(12, 0, "收费员", headerFormat));

        sheet01.addCell(cell01);
        sheet01.addCell(cell02);
        sheet01.addCell(cell03);
        sheet01.addCell(cell04);
        sheet01.addCell(cell05);
        sheet01.addCell(cell06);
        sheet01.addCell(cell07);
        sheet01.addCell(cell08);
        sheet01.addCell(cell09);
        sheet01.addCell(cell10);
        sheet01.addCell(cell11);
        sheet01.addCell(cell12);
//        sheet01.setColumnView(0, 20);
//        sheet01.setColumnView(1, 35);
//        sheet01.setColumnView(2, 15);

        // 写入文件
        workbook01.write();
        // 关闭文件
        workbook01.close();

//        ProcessBuilder pb = new ProcessBuilder("D:\\Dict\\YoudaoDict.exe", "arg1", "arg2");
//
//        // 启动进程
//        Process process = pb.start();
//
//        // 读取进程的输出
//        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//        String line;
//        while ((line = reader.readLine()) != null) {
//            System.out.println(line);
//        }
//
//        // 等待进程结束
//        int exitCode = process.waitFor();
//        System.out.println("Exit Code: " + exitCode);

        return toAjax(1);
    }

    //附件14
    @GetMapping("/downloadProof/{costId}")
    public AjaxResult downloadProof(@PathVariable("costId") Long costId) throws Exception {
        ParameterSingleVO parameterSingleVO = new ParameterSingleVO();
        HouseCostT houseCostT = houseCostQueryTService.selectHouseCostTByCostId(costId);
        if(houseCostT.getUserName()!=null){
            houseCostT.setUserName(MD5.decrypt(houseCostT.getUserName()));
        }
        if(houseCostT.getTel()!=null){
            houseCostT.setTel(MD5.decrypt(houseCostT.getTel()));
        }
        if(houseCostT.getPapersCode()!=null){
            houseCostT.setPapersCode(MD5.decrypt(houseCostT.getPapersCode()));
        }
        Map map = new HashMap();
        map.put("doorAddr", houseCostT.getAddr());
        map.put("userName", houseCostT.getUserName());
        map.put("papersCode", houseCostT.getPapersCode());
        map.put("houseId", houseCostT.getHouseId());
        map.put("tel", houseCostT.getTel());
        map.put("space", String.valueOf(houseCostT.getSpace()));
        map.put("price",String.valueOf(houseCostT.getPrice()));
        map.put("year", houseCostT.getYear());
        map.put("month", houseCostT.getMonth());
        map.put("day", houseCostT.getDay());
        map.put("costMoney", String.valueOf(houseCostT.getCostMoney()));
        map.put("balance", String.valueOf(houseCostT.getBalance()));
        map.put("nowYear", DateFormater.getSystemCurrentDateYYYY());
        map.put("nowMonth", DateFormater.getSystemCurrentDateMM());
        map.put("nowDay", DateFormater.getSystemCurrentDateDD());
        map.put("hour", DateFormater.getSystemCurrentDateHour());
        map.put("minute", DateFormater.getSystemCurrentDateMinute());
        map.put("second", DateFormater.getSystemCurrentDateSecond());
        parameterSingleVO.setParamCode(SysParamKey.PRINT.getKey());
        ParameterSingleVO ss = houseProjectTService.getSysParams(parameterSingleVO);
        String path = ss.getParamVal();
        targetFileName = "cost.doc";
        generateFileName = "维修资金管理中心信息查询证明" + DateFormater.getSystemCurrentDateFull() + ".doc";
        String filePath = path + generateFileName;
        try {
            DocUtils.writeWord(map, path, targetFileName, generateFileName);
            FileUtil.downFile(path + generateFileName, generateFileName, response);
        } catch (Exception e) {
        }
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("addr",urlWord + generateFileName);
        return AjaxResult.success(map1);
    }
}
